package com.woniuxy.charin.controller;



import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.charin.enumeration.Assert;
import com.woniuxy.charin.enumeration.BusinessCode;
import com.woniuxy.charin.model.dto.UserAddDto;
import com.woniuxy.charin.model.dto.UserInfoDto;
import com.woniuxy.charin.model.entity.Permission;
import com.woniuxy.charin.model.entity.User;
import com.woniuxy.charin.model.vo.LoginRequest;
import com.woniuxy.charin.model.vo.UserInfoVo;
import com.woniuxy.charin.model.vo.UserVo;
import com.woniuxy.charin.service.UserService;
import com.woniuxy.charin.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户登录")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     *分页查询用户
     * @param userInfoDto
     * @return
     */
    @PostMapping("/page")
    @ApiOperation("分页查询用户")
    public ResponseEntity<?> page(@RequestBody UserInfoDto userInfoDto) {
        //调用业务层查询
        Page<UserInfoVo> page = userService.queryUser(userInfoDto);
        return ResponseEntity.ok(page);
    }


    /**
     * 上传头像
     * @param
     * @return
     */
    @PutMapping("/updateUrl/{url}")
    @ApiOperation("上传头像")
    public ResponseEntity<?> updateUrl(@PathVariable String url,
                                       @RequestHeader(required = false, name = "Authorization") String authorization){
        Long userId = Long.valueOf(jwtUtil.getValue(authorization, "userId"));
        User user = new User();
        user.setId(userId);
        url = "http://sp6zi9loh.hn-bkt.clouddn.com/"+url;
        user.setAvatarUrl(url);
        userService.updateById(user);
        return ResponseEntity.ok("上传成功");
    }

    /**
     * 删除头像
     */
    @DeleteMapping("/deleteUrl")
    @ApiOperation("删除头像")
    public ResponseEntity<?> deleteUrl(@RequestHeader(required = false, name = "Authorization") String authorization){
        Long userId = Long.valueOf(jwtUtil.getValue(authorization, "userId"));
        User user = new User();
        user.setId(userId);
        user.setAvatarUrl("");
        userService.updateById(user);
        return ResponseEntity.ok("删除成功");
    }


    /**
     * 根据用户得到权限菜单
     * @param authorization
     * @return
     */
    @GetMapping("/getNaviMenuByUser")
    @ApiOperation("根据用户得到权限菜单")
    public ResponseEntity<?> getNaviMenuByUser(
            @RequestHeader(required = false, name = "Authorization") String authorization){
        Long userId = Long.valueOf(jwtUtil.getValue(authorization, "userId"));
        List<Permission> permissionMenus = userService.getNaviMenuByUser(userId);
        return ResponseEntity.ok(permissionMenus);
    }


    /**
     * 判断用户是否登录
     * 数据从请求头中获取Token数据
     */
    @GetMapping("/isLogged")
    @ApiOperation("判断用户是否登录")
    public ResponseEntity<?> isLogged(@RequestHeader(required = false, name = "Authorization") String authorization) {
        log.info("用户请求头中携带的Token是：{}", authorization);
        //如果为空表示没有登录
        Assert.error(StringUtils.isEmpty(authorization), BusinessCode.USER_NOT_LOGGED);
        //判断Token是否有效
        boolean isValid = jwtUtil.validateToken(authorization);
        Assert.error(!isValid, BusinessCode.INVALID_TOKEN);
        //获取用户的ID
        Long userId = Long.valueOf(jwtUtil.getValue(authorization, "userId"));
        //调用业务层查询用户是否存在
        UserVo user = userService.findById(userId);
        return ResponseEntity.ok(user);
    }


    /**
     * 用户名和密码，验证码登录
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseEntity<?> login(@RequestBody LoginRequest param, HttpServletRequest request) {
        //1.调用业务层进行登录
        UserVo userVo = userService.login(param, request);
        return ResponseEntity.ok(userVo);
    }

    /**
     * 图片验证码
     */
    @GetMapping("/code")
    @ApiOperation("生成图片验证码")
    public ResponseEntity generateCaptcha() {
        Map<String, String> data = userService.getCode();
        return ResponseEntity.ok(data);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    @ApiOperation("添加用户")
    public ResponseEntity<?> addUser(@RequestBody UserAddDto userAddDto,
                                     @RequestHeader(required = false, name = "Authorization") String authorization) {
        Long userId = Long.valueOf(jwtUtil.getValue(authorization, "userId"));
        userService.addUser(userAddDto,userId);
        return ResponseEntity.ok("添加成功");
    }

    /**
     * 编辑用户
     */
    @PutMapping("/edit")
    @ApiOperation("编辑用户")
    public ResponseEntity<?> editUser(@RequestBody UserInfoVo userInfoVo) {
        userService.updadteUser(userInfoVo);
        return ResponseEntity.ok("编辑成功");
    }

    /**
     * 批量锁定
     * @param deleteIds
     * @return
     */
    @PostMapping("/batchLock")
    public ResponseEntity<?> batchLock(@RequestBody Integer[] deleteIds) {
        userService.batchLock(deleteIds);
        return ResponseEntity.ok("批量锁定成功");
    }

    /**
     * 锁定
     * @param id
     * @return
     */
    @DeleteMapping("/lock/{id}")
    @ApiOperation("锁定")
    public ResponseEntity<?> lock(@PathVariable Integer id) {
        userService.lock(id);
        return ResponseEntity.ok("锁定成功");
    }

    /**
     * 批量激活
     * @param deleteIds
     * @return
     */
    @PostMapping("/batchActivate")
    @ApiOperation("批量激活")
    public ResponseEntity<?> batchActivate(@RequestBody Integer[] deleteIds) {
        userService.batchActivate(deleteIds);
        return ResponseEntity.ok("批量激活成功");
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseEntity<?> logout(@RequestHeader(required = false, name = "Authorization") String authorization,
                                    HttpServletRequest request) {
        userService.logout(authorization,request);
        return ResponseEntity.ok("退出成功");
    }




}